<?php

class HTML_Fluent_XHTML_Factory extends HTML_Fluent_Factory {

    protected $elementObjectList = array();

    protected $serializer;

    public function __construct() {
        $this->serializer = new HTML_Fluent_Serializer();
    }

    public function injectElement($elementName, HTML_Fluent_Element $element) {
        $this->elementObjectList[$elementName] = $element;
    }

    public function newElement($elementName, $children = array()) {
        if (!isset($this->elementObjectList[$elementName])) {
            $elementNameUpper = strtoupper($elementName);
            $className = "HTML_Fluent_XHTML_Element_$elementNameUpper";
            if (!class_exists($className)) {
                throw new HTML_Fluent_Exception("Element $elementName does not exist.");
	    }
	    $element = new $className($this);
            $this->elementObjectList[$elementName] = $element;
        }

        $element = clone $this->elementObjectList[$elementName];

        foreach ($children as $childNode) {
            if (is_string($childNode)) {
                $childNode = new HTML_Fluent_Text($childNode);
            }
            if ($childNode instanceof HTML_Fluent_Node) {
                $element->addChildNode($childNode);
            }
        }

        return $element;
    }

    public function injectSerializer(HTML_Fluent_Serializer $serializer) {
        $this->serializer = $serializer;
    }

    public function newSerializer() {
        return clone $this->serializer;
    }
}
